package com.yhy.common.action;

import com.google.common.collect.Sets;
import com.yhy.common.dto.AppReturnMsg;
import com.yhy.common.dto.BaseDTO;
import com.yhy.common.dto.ReturnCode;
import com.yhy.common.utils.ITransationExecutor;
import com.yhy.common.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 19-11-20 下午2:39 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2019<br>
 *  *
 *
 */

public abstract class BaseAction<T extends BaseDTO> {

	protected Logger LOGGER = LoggerFactory.getLogger(getClass());

	protected String result2Json(String returnCode, Object content) {
		return result2Json(returnCode, null, content,null);
	}

	protected String result2Json(String returnCode, String token, Object content) {
		return result2Json(returnCode, null, content,token);
	}

	protected String result2Json(String returnCode, String message,Object content, String token) {
		return JsonUtils.toJson(new AppReturnMsg(returnCode, message, content, token));
	}


	protected AppReturnMsg multTransactionExecute(HttpServletRequest request, HttpServletResponse response, T baseDTO, ITransationExecutor<Boolean, String> transationExecutor) {
		List<String> baseEntities = baseDTO.getIdList();

		int len = baseEntities.size();
		String errorMsg = "";
		String allErrorMsg = "";
		int errorNum = 0;
		Set<String> busIds = Sets.newHashSet();

		for (String busId : baseEntities) {
			try {
				if (busIds.contains(busId)) {
					continue;
				}
				transationExecutor.execute(busId);
				busIds.add(busId);
			} catch (Exception e) {
				allErrorMsg = allErrorMsg + "<br>" + e.getMessage();
				LOGGER.error(allErrorMsg, e);
				errorNum++;
			}
		}
		errorMsg = "总处理记录:" + len + "，成功" + (len-errorNum) + "条，失败" + (errorNum > 0 ? "<font color='red'>" + errorNum + "</font>条" + "<font color='#FFB90F'>" + allErrorMsg + "</font>" : "0条") ;
		return new AppReturnMsg(ReturnCode.SUCCESS_CODE.getCode(),errorMsg,null);
	}

}
